/*
 * @Author: zhangduo 445629906@qq.com
 * @Date: 2023-10-12 19:16:58
 * @LastEditors: zhengjingjing 1742420988@qq.com
 * @LastEditTime: 2025-02-12 10:42:55
 * @FilePath: \greencity-ui\src\store\modules\user.js
 * @Description:
 *
 * Copyright (c) 2024 by zhangduo, All Rights Reserved.
 */
import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    nickName: "",
    deptId: "",
    dataScope: "",
    phonenumber:"",
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName;
    },
    SET_DEPTID: (state, deptId) => {
      state.deptId = deptId;
    },
    SET_DATASCOPE: (state, dataScope) => {
      state.dataScope = dataScope;
    },
    SET_phonenumber: (state, phonenumber) => {
      state.phonenumber = phonenumber;
    },
  },
  //   increment (context) {
  //     context.commit('increment')
  // }
  //   ES2015 的 参数解构(opens new window)来简化代码
  //   increment ({ commit }) {
  //   commit('increment')
  // }
  actions: {
    // 登录  { commit }
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((res) => {
            setToken(res.token);
            commit("SET_TOKEN", res.token);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            // 替换id属性，以适配java及node.js版本后台权限api
            res.user = JSON.parse(
              JSON.stringify(res.user).replace("id", "userId")
            );
            res.user.roles = JSON.parse(
              JSON.stringify(res.user.roles).replaceAll("id", "roleId")
            );
            const user = res.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? require("@/assets/images/profile.jpg")
                : // : process.env.VUE_APP_BASE_API + user.avatar;
                  window.mapConfig.psmUrl + user.avatar;
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", user.userName);
            commit("SET_AVATAR", avatar);
            commit("SET_NICKNAME", user.nickName);
            commit("SET_DEPTID", user.deptId);
            commit("SET_phonenumber", user.phonenumber);
            // 配置数据权限过滤条件
            let sqlString = undefined;
            for (const role of res.user.roles) {
              // if(role.dataScope==1)
              switch (role.dataScope) {
                // 全部数据权限
                case "1":
                  continue;
                // 自定数据权限
                case "2":
                  sqlString = ` OR dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = ${role.roleId} ) `;
                  break;
                // 部门数据权限
                case "3":
                  sqlString = ` OR dept_id = ${user.deptId} `;
                  break;
                // 部门及以下数据权限
                case "4":
                  sqlString = ` OR dept_id = ${user.deptId} or dept_id in (SELECT dept_id FROM sys_dept WHERE ${user.deptId} || '' = ANY(STRING_TO_ARRAY(ancestors, ','))) `;
                  break;
                // 仅本人数据权限
                case "5":
                  sqlString = ` OR user_id = ${user.userId} `;
                  break;
                default:
                  break;
              }
            }
            if (sqlString != undefined) sqlString = ` (${sqlString.substring(4)})`;
            console.log(sqlString);
            commit("SET_DATASCOPE", sqlString);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
